package spittr.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import spittr.Spittle;
import spittr.data.SpittleRepository;
import spittr.exception.SpitterNotFoundException;

@Controller
@RequestMapping("/spittle")
public class SpittleController {

    private SpittleRepository spittleRepository;

    @Autowired
    public SpittleController(SpittleRepository spittleRepository) {
        this.spittleRepository = spittleRepository;
    }


    /**
     * 获取部分spittle
     * @param max
     * @param count
     * @param model
     * @return
     */
    @RequestMapping(value = "/getList",method = RequestMethod.GET)
    public String spittles(@RequestParam(value = "max") Long max, @RequestParam(value = "count",defaultValue = "20") int count,Model model){
        System.out.println("spittles");
        model.addAttribute("spittleList",spittleRepository.findSpittles(max, count));
        return "spittles";
    }



    /**
     * 根据ID获取详情
     * @param spittleId
     * @return
     */
    @RequestMapping(value = "/{spittleId}")
    public String spittle(@PathVariable long spittleId, Model model) {
        System.out.println("spittle");
        Spittle spittle = spittleRepository.findByID(spittleId);
        model.addAttribute("spittle",spittle);
        return "spittle";
    }


    /**
     * 异常处理测试类
     */
    @RequestMapping(value = "/do",method = RequestMethod.GET)
    public void exceptioTest(){
        throw new SpitterNotFoundException();
    }



}
